import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

// 商品管理界面的类
public class ManageProductFrame extends JFrame {
    private JTable contactsTable;  // 表格
    private JTextField searchField;  // 搜索框

    // 构造方法，设置界面基本属性
    public ManageProductFrame() {
        setTitle("商品管理");  // 设置界面标题
        setSize(800, 600);  // 设置界面大小
        setLocationRelativeTo(null);  // 将界面居中显示
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  // 设置关闭操作,结束窗口程序

        JPanel panel = new JPanel(new BorderLayout());  // 创建面板，使用边界布局
        add(panel);  // 将面板添加到界面

        // 创建一个空的表格模型
        DefaultTableModel tableModel = new DefaultTableModel(
                new Object[][]{},
                new Object[]{"商品编号", "商品名称", "生产厂家", "生产日期", "型号", "进货价", "零售价格", "数量"}//列名
        );

        // 创建表格
        contactsTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(contactsTable);//把表格添加到滚动窗格里面
        panel.add(scrollPane, BorderLayout.CENTER);

        // 添加用于增删改查操作和搜索的组件
        JButton addButton = new JButton("添加");  // 创建“添加”按钮
        JButton deleteButton = new JButton("删除");  // 创建“删除”按钮
        JButton updateButton = new JButton("修改");  // 创建“修改”按钮
        JButton searchButton = new JButton("搜索");  // 创建“搜索”按钮
        JButton backButton = new JButton("返回管理员菜单界面");  // 创建登出按钮

        JPanel buttonPanel = new JPanel();  // 创建按钮面板，使用默认的FlowLayout布局
        buttonPanel.add(addButton);       //添加添加按钮
        buttonPanel.add(deleteButton);       //添加删除按钮
        buttonPanel.add(updateButton);       //添加修改按钮
        searchField = new JTextField(20);  // 创建搜索框
        buttonPanel.add(searchField);
        buttonPanel.add(searchButton);      //添加搜索按钮
        buttonPanel.add(backButton);//添加返回按钮

        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 添加“添加”按钮的监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addProducts();  // 执行添加联系人操作
            }
        });

        // 添加“删除”按钮的监听器
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteProducts();  // 执行删除联系人操作
            }
        });

        // 添加“更新”按钮的监听器
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateProducts();  // 执行更新联系人操作
            }
        });

        // 添加“搜索”按钮的监听器
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchProducts(searchField.getText());  // 执行搜索联系人操作
            }
        });
        //添加"返回"按钮的监听器
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();  // 关闭当前窗口
                AdminMenuFrame adminMenuFrame =new AdminMenuFrame();
                adminMenuFrame.setVisible(true);
            }
        });
        // 初始化表格内容

        refreshTable();  // 刷新表格显示
    }

    //添加商品信息的方法
    private void addProducts() {
        // 从用户输入中获取商品信息
        String productName = JOptionPane.showInputDialog("请输入商品名称:");
        String changJia = JOptionPane.showInputDialog("请输入商品厂家:");
        String productDateStr = JOptionPane.showInputDialog("请输入商品生产日期（格式为yyyy-MM-dd HH:mm:ss）:");
        String type = JOptionPane.showInputDialog("请输入商品型号:");

        // 获取并解析进货价、零售价格和数量
        double purchasePrice = 0.0;
        double retailPrice = 0.0;
        int quantity = 0;

        try {
            purchasePrice = Double.parseDouble(JOptionPane.showInputDialog("请输入商品的进货价:"));
            retailPrice = Double.parseDouble(JOptionPane.showInputDialog("请输入商品的零售价格:"));
            quantity = Integer.parseInt(JOptionPane.showInputDialog("请输入商品的数量:"));
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "价格或数量格式错误，请输入有效的数字。", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 处理生产日期
        Timestamp productDate;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            productDate = new Timestamp(dateFormat.parse(productDateStr).getTime());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "生产日期格式错误，请使用 yyyy-MM-dd HH:mm:ss 格式。", "日期格式错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 确保商品名称不为空
        if (productName != null && !productName.trim().isEmpty()) {
            Connection connection = null;
            try {
                connection = DBUtil.getConnection();
                int maxId = getMaxId(connection, "Products");
                String sql = "INSERT INTO products (product_id, productname, changjia, product_at, type, purchaseprice, retailprice, quantity) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                    preparedStatement.setInt(1, maxId + 1);
                    preparedStatement.setString(2, productName);
                    preparedStatement.setString(3, changJia);
                    preparedStatement.setTimestamp(4, productDate);
                    preparedStatement.setString(5, type);
                    preparedStatement.setDouble(6, purchasePrice);
                    preparedStatement.setDouble(7, retailPrice);
                    preparedStatement.setInt(8, quantity);

                    int affectedRows = preparedStatement.executeUpdate();
                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "商品添加成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                        refreshTable();
                    } else {
                        JOptionPane.showMessageDialog(this, "商品添加失败，请重试。", "失败", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DBUtil.closeConnection(connection);
            }
        } else {
            JOptionPane.showMessageDialog(this, "商品名称不能为空。", "输入错误", JOptionPane.ERROR_MESSAGE);
        }
    }


    // 获取指定表的最大ID值的方法
    private int getMaxId(Connection connection, String tableName) throws SQLException {
        String sql = "SELECT MAX(product_id) AS max_id FROM " + tableName;  // 构建查询最大ID的SQL语句
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            ResultSet resultSet = preparedStatement.executeQuery();  // 执行查询操作
            if (resultSet.next()) {
                return resultSet.getInt("max_id");  // 返回查询结果中的最大ID值
            }
        }
        return 0; // 如果查询失败，返回默认值
    }

    //删除商品的方法
    private void deleteProducts() {
        int selectedRow = contactsTable.getSelectedRow();  // 获取选中行的索引
        if (selectedRow != -1) {
            // 获取选中行商品名称
            String productName = (String) contactsTable.getValueAt(selectedRow, 1);  // 假设商品名称在第二列

            // 弹出确认对话框
            int option = JOptionPane.showConfirmDialog(this,
                    "确定要删除商品 \"" + productName + "\" 吗？删除后无法恢复！",
                    "确认删除",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE);

            if (option == JOptionPane.YES_OPTION) {
                Connection connection = null;
                try {
                    connection = DBUtil.getConnection();
                    String sql = "DELETE FROM products WHERE productname = ?";
                    try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                        preparedStatement.setString(1, productName);
                        int affectedRows = preparedStatement.executeUpdate();
                        if (affectedRows > 0) {
                            JOptionPane.showMessageDialog(this, "商品删除成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                            refreshTable();  // 刷新表格显示
                        } else {
                            JOptionPane.showMessageDialog(this, "商品删除失败，请重试。", "失败", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    DBUtil.closeConnection(connection);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要删除的商品。", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }


    // 修改选中的商品的方法
    private void updateProducts() {
        // 从用户输入中获取商品编号
        String productIdStr = JOptionPane.showInputDialog("请输入要更新的商品编号:");
        int productId;

        try {
            productId = Integer.parseInt(productIdStr);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "商品编号格式错误，请输入有效的数字。", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 从用户输入中获取其他商品信息
        String productName = JOptionPane.showInputDialog("请输入商品名称:");
        String changJia = JOptionPane.showInputDialog("请输入商品厂家:");
        String productDateStr = JOptionPane.showInputDialog("请输入商品生产日期（格式为yyyy-MM-dd HH:mm:ss）:");
        String type = JOptionPane.showInputDialog("请输入商品型号:");

        double purchasePrice = 0.0;
        double retailPrice = 0.0;
        int quantity = 0;

        try {
            purchasePrice = Double.parseDouble(JOptionPane.showInputDialog("请输入商品的进货价:"));
            retailPrice = Double.parseDouble(JOptionPane.showInputDialog("请输入商品的零售价格:"));
            quantity = Integer.parseInt(JOptionPane.showInputDialog("请输入商品的数量:"));
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "价格或数量格式错误，请输入有效的数字。", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 处理生产日期
        Timestamp productDate;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            productDate = new Timestamp(dateFormat.parse(productDateStr).getTime());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "生产日期格式错误，请使用 yyyy-MM-dd HH:mm:ss 格式。", "日期格式错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 确保商品名称不为空
        if (productName != null && !productName.trim().isEmpty()) {
            Connection connection = null;
            try {
                connection = DBUtil.getConnection();
                String sql = "UPDATE products SET productname = ?, changjia = ?, product_at = ?, type = ?, purchaseprice = ?, retailprice = ?, quantity = ? WHERE product_id = ?";
                try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                    preparedStatement.setString(1, productName);
                    preparedStatement.setString(2, changJia);
                    preparedStatement.setTimestamp(3, productDate);
                    preparedStatement.setString(4, type);
                    preparedStatement.setDouble(5, purchasePrice);
                    preparedStatement.setDouble(6, retailPrice);
                    preparedStatement.setInt(7, quantity);
                    preparedStatement.setInt(8, productId);

                    int affectedRows = preparedStatement.executeUpdate();
                    if (affectedRows > 0) {
                        JOptionPane.showMessageDialog(this, "商品信息更新成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                        refreshTable();
                    } else {
                        JOptionPane.showMessageDialog(this, "未找到该商品编号或更新失败，请重试。", "失败", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DBUtil.closeConnection(connection);
            }
        } else {
            JOptionPane.showMessageDialog(this, "商品名称不能为空。", "输入错误", JOptionPane.ERROR_MESSAGE);
        }
    }


    //根据关键字查询商品
    private void searchProducts(String keyword) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtil.getConnection();  // 获取数据库连接

            String likeKeyword = "%" + keyword + "%";
            String sql = "SELECT product_id, productname, changjia, product_at, type, purchaseprice, retailprice, quantity " +
                    "FROM products WHERE product_id LIKE ? OR productname LIKE ? OR changjia LIKE ? OR product_at LIKE ? OR type LIKE ?";
            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setString(1, likeKeyword);
            preparedStatement.setString(2, likeKeyword);
            preparedStatement.setString(3, likeKeyword);
            preparedStatement.setString(4, likeKeyword);
            preparedStatement.setString(5, likeKeyword);

            resultSet = preparedStatement.executeQuery();

            DefaultTableModel model = (DefaultTableModel) contactsTable.getModel();
            model.setRowCount(0);

            while (resultSet.next()) {
                model.addRow(new Object[]{
                        resultSet.getInt("product_id"),
                        resultSet.getString("productname"),
                        resultSet.getString("changjia"),
                        resultSet.getTimestamp("product_at"),
                        resultSet.getString("type"),
                        resultSet.getDouble("purchaseprice"),  // 添加商品进价
                        resultSet.getDouble("retailprice"), // 添加商品零售价
                        resultSet.getInt("quantity")          // 添加商品数量
                });
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库操作失败: " + e.getMessage());
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                if (preparedStatement != null) preparedStatement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 刷新表格显示所有联系人的方法
    private void refreshTable() {
        Connection connection = null;
        try {
            connection = DBUtil.getConnection();  // 获取数据库连接
            String sql = "SELECT * FROM products";  // 构建查询所有商品的SQL语句
            try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
                ResultSet resultSet = preparedStatement.executeQuery();  // 执行查询操作
                updateTable(resultSet);  // 更新表格显示
            }
        } catch (SQLException e) {
            e.printStackTrace();  // 打印异常信息
        } finally {
            DBUtil.closeConnection(connection);  // 关闭数据库连接
        }
    }

    // 更新表格内容
    private void updateTable(ResultSet resultSet) throws SQLException {
        DefaultTableModel tableModel = (DefaultTableModel) contactsTable.getModel();  // 获取表格模型
        tableModel.setRowCount(0); // 清空表格

        while (resultSet.next()) {
            Object[] rowData = {
                    resultSet.getInt("product_id"),
                    resultSet.getString("productname"),
                    resultSet.getString("changjia"),
                    resultSet.getDate("product_at"),
                    resultSet.getString("type"),
                    resultSet.getDouble("purchaseprice"),
                    resultSet.getDouble("retailprice"),
                    resultSet.getInt("quantity")
            };
            tableModel.addRow(rowData);  // 向表格模型添加一行数据
        }
    }

}